#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include"inc/app.h"
#include"inc/game.h"
#include"inc/tem.h"
#include"inc/game2048.h"
#include"inc/pthread.h"
int board_state[15][15] = {{0}};
Gnode *global_list = NULL;
// 声明软件盒容器（
extern lv_obj_t* app_container;
//extern lv_obj_t* scr;
//五子棋
void *game(void *arg)
{
    
    pthread_mutex_lock(&ui_mutex);
    //lv_obj_clean(lv_scr_act());
    // 初始化游戏状态

        global_list = create_doublelist();
    
   // lv_obj_t* screen2=lv_scr_act();
    memset(board_state, 0, sizeof(board_state));
    game_over = 0;
    // 先创建游戏主界面
    create_chessboard(screen);
    create_control_panel(screen);
    
    // 最后创建启动界面（会覆盖在上面）
    gamestart(screen);
    update_game_info();
    

    pthread_mutex_unlock(&ui_mutex);
   
   // lv_refr_now(NULL);
    //pthread_exit(NULL);
    return NULL;
}

//2048
void *game2(void *arg)
{
    pthread_mutex_lock(&ui_mutex);

     /* lv_init();
    srand(time(NULL));
    
    //设备初始化
    lv_display_t *disp = lv_linux_fbdev_create();
    lv_linux_fbdev_set_file(disp, "/dev/fb0");
    lv_indev_t * indev = lv_evdev_create(LV_INDEV_TYPE_POINTER,"/dev/input/event0");*/


    
    
     
    //初始化游戏UI
    ui_init();
    
    score=0;
    ev.flag2=0;
    p = game_start();

    //读档
    game_read(p,&score);
    if(game_is_over(p)==false)
    {
        score=0;
        for(int i=0;i<4;i++) free(p[i]);
        free(p);
        p=game_start();
    }

    //首次显示
    ui_update(p);  
    
    //主游戏循环
    while (1)
    {
        lv_timer_handler();

        hide_bmp_fullscreen();

        if(game_is_over(p))
        {
            if(ev.flag==0||ev.way==OTH) continue;
        
            // 处理游戏逻辑
            block_synthesis(&ev, p);
            if (!game_is_over(p)) break;
            
            // 生成新数字
            int *empty = rand_empty(p);
            if (empty) *empty=rand_2_or_4();
            
            // 更新界面
            ui_update(p);

            //修改标志位
            ev.flag=0;

            // 控制刷新率
            usleep(10000);

        }
        else
        {
            //游戏结束处理
            ev.flag2=1;
           // show_bmp_fullscreen("A:/zqz/gameover.bmp",480,480);
            lv_timer_handler(); 
            usleep(10000);  //不加重开后全空
            continue;
        }
        
    }


    pthread_mutex_unlock(&ui_mutex);
}

//环境检测
void *tem(void *arg)
{
    pthread_mutex_lock(&ui_mutex);
   
    pthread_mutex_unlock(&ui_mutex);
    // lv_timer_create(tem_timer_cb, 1000, NULL);
   return NULL;
  // tem_ui_requested = 1; // 请求主线程创建 UI
    //return NULL;
}
